﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DARE.Save.DataStructures
{
    public class CHUDData: ISaveData
    {
        public string Name;
        public Dictionary<string, CWidgetData> Widgets = new Dictionary<string,CWidgetData>();
        public CCursorData m_cursor;

        public void FillDataStructure(object hud)
        {
            Name = (hud as CHUDSystem).Name;
            m_cursor = new CCursorData();
            m_cursor.FillDataStructure((hud as CHUDSystem).Cursor);
            foreach (CWidget wid in (hud as CHUDSystem).DisplayList)
            {
                CWidgetData wd = CWidgetData.CreateWidgetDataType(wid);
                wd.FillDataStructure(wid);
                Widgets.Add(wd.name, wd);
            }
        }

        public void FillFromDataStructure(out object hudsys, params object[] paramsData)
        {
            CHUDSystem hud = new CHUDSystem(Name);
            CCursor c = new CCursor(hud);
            m_cursor.FillFromDataStructure(c);
            Dictionary<CWidgetData, CWidget> wids = new Dictionary<CWidgetData, CWidget>();
            foreach (CWidgetData widData in Widgets.Values)
            {
                Type t = Type.GetType(widData.typeFullName);
                if (t == null)
                    t = typeof(CWidget);

                CWidget wid = hud.GetElement(widData.name);
                if (wid == null)
                {
                    System.Reflection.ConstructorInfo ci = t.GetConstructor(new Type[3] { typeof(DARE.CHUDSystem), typeof(CWidget), typeof(string) });
                    wid = (CWidget)ci.Invoke(new object[3] { hud, null, widData.name });
                }
                bool replace = false;
                foreach (CWidgetData wdata in wids.Keys)
                    if (wdata.name == wid.Name)
                    {
                        hud.Remove(wdata.name);
                        hud.Add(wid);
                        wid.HUD = hud;
                        wids[wdata] = wid;
                        replace = true;
                        break;
                    }
                if (!replace)
                    wids.Add(widData, wid);
            }

            foreach (KeyValuePair<CWidgetData, CWidget> wid in wids)
            {
                CWidget w = wid.Value;
                wid.Key.FillFromDataStructure(ref w, hud);
            }
            hudsys = hud;
        }
    }
}
